package storage.indexing.bTree;

import represent.type.Type;
import utils.Lib;

public class BTreeInternalNode<T extends Type> extends BTreeNode<T> {

	private BTreeNode<T>[] pointers = new BTreeNode[POINTER_COUNT];
	
	public BTreeInternalNode(BTree<T> tree) {
		super(tree);
	}
	
	public BTreeInternalNode(BTreeInternalNode<T> father) {
		super(father);
	}
	
	@Override
	protected BTreeNode<T> createNode() {
		return new BTreeInternalNode<T>(this.father);
	}
	
	@Override
	protected void update(BTreeNode<T> next, int pos) {
		Lib.assertTrue(next instanceof BTreeInternalNode<?>);
		BTreeInternalNode<T> iNext = (BTreeInternalNode<T>) next;
		
		// update keys and pointers for internal node
		iNext.pointers[0] = pointers[pos];
		for (int i = pos + 1; i < POINTER_COUNT; ++i) {
			iNext.keys[i - pos - 1] = keys[i];
			keys[i] = null;
			iNext.pointers[i - pos] = pointers[i];
			pointers[i] = null;
			--size;
			++next.size;
		}
	}
	
	protected void insertFirst(BTreeNode<T> node) {
		pointers[0] = node;
	}
	
	@Override
	protected void insertKey(T key, int pos, int rid, BTreeNode<T> pointer) {
		// insert key and pointers only
		++size;
		for (int i = size; i > pos; --i) {
//			System.arraycopy(keys, pos, keys, pos + 1, size - pos);
			keys[i] = keys[i - 1];
			pointers[i + 1] = pointers[i];
		}
		keys[pos] = key;
		pointers[pos + 1] = pointer;
	}
	
	protected void deleteKey(T key, int pos, int rid) {
		for (int i = pos + 1; i < size; ++i) {
			keys[i - 1] = keys[i];
			pointers[i] = pointers[i + 1];
		}
		--size;
	}
}
